package cn.qy.java.base.ch21;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @auther acc8226
 */
public class Ch21_00_ThreadCreate {

	public static void main(String[] args) throws InterruptedException {
		// 1. 通过继承 Thread 类
		Thread t1 = new Thread() {
			public void run() {
				System.out.println("thread 1");
			};
		};
		t1.start();

		// 2. 通过实现 Runnable 接口
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				System.out.println("thread 2");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				// 该句话不会执行，因为以下已经设为 守护进程
				System.out.println("thread 2 is end");
			}
		};
		// 设置守护进程
		Thread t2 = new Thread(runnable);
		t2.setDaemon(true);
		t2.start();

		// 3. 通过构建 FutureTask 对象
		Callable<String> callable = new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(1000);
				return "thread 3";
			}
		};
		FutureTask<String> futureTask = new FutureTask<>(callable);
		Thread t3 = new Thread(futureTask);
		t3.start();
		// get 会一直等待，直到获取任务结果
		try {
			System.out.println(futureTask.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		
		// 4 线程的状态
		Thread t = new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		System.out.println(t.getState());

		t.start();
		System.out.println(t.getState());
		
		Thread.sleep(1000);
		System.out.println(t.getState());
		
		Thread.sleep(5000);
		System.out.println(t.getState());
	}
	
	

}
